package com.hrpc.serialize.impl;

import com.hrpc.exceptions.SerializeException;
import com.hrpc.serialize.Serialize;

import java.io.*;

/**
 * 序列化和反序列化 对应 写出去 和 读进来
 */
public class JDKSerializeImpl implements Serialize {
    @Override
    public byte[] serialize(Object object) {
        if (object == null){
            return null;
        }
        try(//将流的定义写在这里会自动关闭，不需要再写final了
                ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream)
        ) {
            objectOutputStream.writeObject(object);
            return byteArrayOutputStream.toByteArray();
        }catch (IOException e){
            throw new SerializeException("JDK序列化时出错了！！！");
        }
    }

    @Override
    public <T> T deSerialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null ||clazz == null){
            return null;
        }
        try(//将流的定义写在这里会自动关闭，不需要再写final了
            ByteArrayInputStream byteArrayinputStream=new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayinputStream)
        ) {
            Object object = objectInputStream.readObject();
            return (T) object;
        }catch (IOException | ClassNotFoundException e){
            throw new SerializeException("JDK反序列化时出错了！！！");
        }
    }
}
